package org.ziwei.rule.api;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.ziwei.paipan.MingPan;
import org.ziwei.rule.dao.RuleRepository;
import org.ziwei.rule.pojo.Rule;
import org.ziwei.rule.util.RuleUtils;

@Component("ruleHandlerChain")
public class RuleHandlerChain{

	private static final Log logger = LogFactory.getLog(RuleHandlerChain.class);
	
	private boolean init = false;
	
	private List<RuleHandler> handlerList = new ArrayList<RuleHandler>();
	
	@Autowired
	private RuleRepository ruleRepository;
	
	public void addHandler(RuleHandler handler) {
		handlerList.add(handler);
	}

	public void addHandler(RuleHandler... handlers) {
		if (!ObjectUtils.isEmpty(handlers)) {
			handlerList.addAll(Arrays.asList(handlers));
		}
	}
	
	public List<RuleHandler> getHandlers() {
		initHandler();
		return this.handlerList;
	}
	
	private void initHandler(){
		if(!init){
			try {
				Collection<RuleHandler> handlers = RuleUtils.getInstanceByInterface(this.getClass().getPackage().getName(), RuleHandler.class);
				handlerList.addAll(handlers);
			} catch (Exception e) {
				logger.error("error in instantiation the rulehandler",e);
				init = false;
			}
			init = true;
		}
	}
	
	public List<Rule> fireAllRules(MingPan pan) throws Exception {
		List<Rule> ruleList = new ArrayList<Rule>();

		List<RuleHandler> handlers = getHandlers();
		if (!ObjectUtils.isEmpty(handlers)) {
			for (int i = 0; i < handlers.size(); i++) {
				RuleHandler handler = handlers.get(i);
				
				List<String> rules = handler.fireRule(pan);
				for(String ruleCode: rules){
					Rule rule = ruleRepository.find(ruleCode);
					ruleList.add(rule);
				}
				
			}
		}
		
		return ruleList;
	}

}
